package com.yun.datastructure.linear.list.linkedlist.leetcode;

import com.yun.datastructure.linear.queue.priorityqueue.ListNodeMinHeap;
import com.yun.datastructure.linear.list.linkedlist.ListNode;

public class Leetcode23 {

    public ListNode mergeTwoLists(ListNode p1, ListNode p2) {
        ListNode s = new ListNode(-1, null);
        ListNode p = s;
        while (p1 != null && p2 != null) {
            if (p1.val < p2.val) {
                p.next = p1;
                p1 = p1.next;
            } else {
                p.next = p2;
                p2 = p2.next;
            }
            p = p.next;
        }
        if (p1 != null) {
            p.next = p1;
        } else {
            p.next = p2;
        }
        return s.next;
    }

    public ListNode mergeKLists1(ListNode[] lists) {
        if (lists.length == 0) {
            return null;
        }
        return split(lists, 0, lists.length-1);
    }

    //返回合并后的链表,i,j代表左右边界
    public ListNode split(ListNode[] lists, int i, int j) {
        if (i == j) {
            return lists[i];
        }
        int m = (i + j) >>> 1;
        ListNode left = split(lists, i, m);
        ListNode right = split(lists, m + 1, j);
        return mergeTwoLists(left, right);
    }

    public ListNode mergeKLists(ListNode[] lists){
        ListNodeMinHeap heap=new ListNodeMinHeap(lists.length);
        for (ListNode h : lists) {
            if(h!=null){
                heap.offer(h);
            }
        }
        ListNode s=new ListNode(-1,null);
        ListNode t=s;
        while (!heap.isEmpty()){
            ListNode min=heap.poll();
            t.next=min;
            t=min;
            if(min.next!=null){
                heap.offer(min.next);
            }
        }
        return s.next;
    }

    public static void main(String[] args) {
        ListNode[] lists = {
                ListNode.of(1, 4, 5),
                ListNode.of(1, 3, 4),
                ListNode.of(2, 6),
        };
        ListNode n1 = new Leetcode23().mergeKLists(lists);
        System.out.println(n1);
    }
}
